package com.yj.ccs.abs.util.file;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Copyright 2018 (C) Yunjian-VC
 * Created on : 2018/2/7
 * Author     : Unbelievable9
 **/
public class ExcelUtils {

    private static DataFormatter formatter = new DataFormatter();

    public static Map<Integer, List<String>> convertToColumnInfoMap(InputStream inputStream) throws IOException {
        Map<Integer, List<String>> dataMap = new HashMap<>();

        Workbook workbook = new XSSFWorkbook(inputStream);
        Sheet sheet = workbook.getSheetAt(0);

        for (Row row : sheet) {
            for (Cell cell : row) {
                if (row.getRowNum() == sheet.getFirstRowNum()) {
                    dataMap.put(cell.getColumnIndex(), new ArrayList<>());
                } else {
                    List<String> columnList = dataMap.get(cell.getColumnIndex());

                    columnList.add(formatter.formatCellValue(cell));
                }
            }
        }

        return dataMap;
    }

    public static Map<Integer, List<String>> convertToRowInfoMap(InputStream inputStream) throws IOException {
        Map<Integer, List<String>> dataMap = new HashMap<>();

        Workbook workbook = new XSSFWorkbook(inputStream);
        Sheet sheet = workbook.getSheetAt(0);

        for (Row row : sheet) {
            if (row.getRowNum() != sheet.getFirstRowNum()) {
                List<String> rowList = new ArrayList<>();

                for (Cell cell : row) {
                    rowList.add(formatter.formatCellValue(cell));
                }

                dataMap.put(row.getRowNum() - 1, rowList);
            }
        }

        return dataMap;
    }
}
